# -*- coding = utf-8 -*-
# @Time    : 2025/6/13 14:41
# @Author  : 杨明明
# @File    : serializers.py
# @Software: PyCharm
from enum import unique

from rest_framework_simplejwt.serializers import TokenObtainPairSerializer, TokenRefreshSerializer
from rest_framework import serializers

from .models import User


# 定义一个自己的TokenObtainPairSerializer序列化器
class MyTokenObtainPairSerializer(TokenObtainPairSerializer):
    def validate(self, attrs):
        data = super().validate(attrs)
        data['token'] = data.pop('access')
        data['username'] = self.user.username
        data['mobile'] = self.user.mobile
        data['sex'] = self.user.sex
        data['id'] = self.user.id
        data['msg'] = '登录成功'
        return data


# 定义一个自己的TokenObtainSerializer序列化器
class MyTokenObtainSerializer(TokenRefreshSerializer):
    def validate(self, attrs):
        data = super().validate(attrs)
        data['token'] = data.pop('access')
        data['msg'] = '刷新token成功'
        return data


# 注册
class RegisterSerializer(serializers.ModelSerializer):
    password_confirm = serializers.CharField(label='确认密码', help_text='请输入确认密码', min_length=6, max_length=20,
                                             required=True, write_only=True, error_messages={
            'min_length': '仅允许6-20个字符的密码',
            'max_length': '仅允许6-20个字符的密码',
            'required': '密码不能为空',
        })

    class Meta:
        model = User
        fields = ('username', 'password', 'password_confirm', 'mobile', 'sex', 'email')
        extra_kwargs = {
            'username': {
                'label': '用户名',
                'help_text': '请输入6-20位长度内的用户名',
                'min_length': 6,
                'max_length': 20,
                'required': True,
                'error_messages': {
                    'min_length': '仅允许6-20个字符的用户名',
                    'max_length': '仅允许6-20个字符的用户名',
                    'required': '用户名不能为空',
                }
            },
            'password': {
                'write_only': True,
                'label': '密码',
                'help_text': '请输入6-20位长度内的密码',
                'min_length': 6,
                'max_length': 20,
                'required': True,
                'error_messages': {
                    'min_length': '仅允许6-20个字符的密码',
                    'max_length': '仅允许6-20个字符的密码',
                    'required': '密码不能为空',
                }
            },
            'mobile': {
                'label': '手机号',
                'help_text': '请输入11位手机号',
                'min_length': 11,
                'max_length': 11,
                'required': True,
                'error_messages': {
                    'min_length': '仅允许11位手机号',
                    'max_length': '仅允许11位手机号',
                    'required': '手机号不能为空',
                }
            },
            'sex': {
                'label': '性别',
                'help_text': '请输入1或2，1为男，2为女',
                'required': True,
                'error_messages': {
                    'required': '性别不能为空',
                }
            },
            'email': {
                'label': '邮箱',
                'help_text': '请输入邮箱',
                'required': True,
                'error_messages': {
                    'required': '邮箱不能为空',
                    'invalid': '邮箱格式错误',
                }
            },
        }

    def validate_email(self, value):  # noqa
        if User.objects.filter(email=value).exists():
            raise serializers.ValidationError('邮箱已存在')
        return value

    def validate(self, attrs):
        if attrs['password'] != attrs['password_confirm']:
            raise serializers.ValidationError('两次输入的密码不一致')
        return attrs

    def create(self, validated_data):
        validated_data.pop('password_confirm')
        return User.objects.create_user(**validated_data)

    def to_representation(self, instance):
        data = super().to_representation(instance)
        sex = data.get('sex')
        if sex == '1':
            data['sex'] = '男'
        elif sex == '2':
            data['sex'] = '女'
        data['msg'] = '注册成功'
        return data
